const API_KEY = 'sk-3534faf8f850402ba09940e4ca99a3ca'; // 需要替换为你的API密钥

export const getAIResponse = async (message) => {
  try {
    const requestPromise = () => {
      return new Promise((resolve, reject) => {
        wx.request({
          url: 'https://api.deepseek.com/v1/chat/completions',
          method: 'POST',
          data: {
            model: "deepseek-chat",
            messages: [{
              role: "user",
              content: message
            }],
            temperature: 0.5, // 降低随机性，提高响应速度
            max_tokens: 1000, // 限制回复长度
            presence_penalty: 0, // 降低重复内容的惩罚
            frequency_penalty: 0, // 降低词频的惩罚
          },
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
          },
          success: (res) => {
            console.log('请求成功，响应数据:', res);
            resolve(res);
          },
          fail: (err) => {
            console.error('请求失败:', err);
            reject(err);
          }
        });
      });
    };

    const response = await requestPromise();

    if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 300) {
      throw new Error(`HTTP请求失败: ${response.statusCode}, ${JSON.stringify(response.data)}`);
    }

    // 详细检查响应数据结构
    if (!response.data) {
      throw new Error('响应数据为空');
    }

    console.log('响应数据结构:', JSON.stringify(response.data, null, 2));

    if (response.data.error) {
      throw new Error(`API错误: ${response.data.error.message || '未知错误'}`);
    }

    if (!response.data.choices) {
      throw new Error('响应中没有choices字段');
    }

    if (!Array.isArray(response.data.choices)) {
      throw new Error('choices不是数组');
    }

    if (response.data.choices.length === 0) {
      throw new Error('choices数组为空');
    }

    if (!response.data.choices[0].message) {
      throw new Error('未找到消息内容');
    }

    return response.data.choices[0].message.content;

  } catch (error) {
    console.error('AI请求详细错误:', {
      error: error.message,
      stack: error.stack,
      response: error.response,
      type: error.type,
      details: error
    });
    throw new Error(`AI服务请求失败: ${error.message}`);
  }
};